package MEET.src.View;
import MEET.src.code.Meeting;
import MEET.src.code.MeetingController;
import com.toedter.calendar.JDateChooser;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class MeetingQueryForm1 extends JFrame {
    private JPanel contentPane;
    private JTextField txtMeetingId;
    private JTextField txtHostName;
    private JTable meetingTable;
    private JTable historyTable;
    private JTabbedPane tabbedPane;
    private JDateChooser startDateChooser;
    private JDateChooser endDateChooser;

    private MeetingController controller = new MeetingController();

    public MeetingQueryForm1() {
        setTitle("上海电力大学会议预订系统 - 会议查询");
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); // 设置关闭操作为隐藏窗口
        setSize(1100, 700);
        setLocationRelativeTo(null);

        // 主面板设置
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 5));
        setContentPane(contentPane);

        // 1. 顶部标题栏
        createHeaderPanel();

        // 2. 导航栏（缩小版）
        createCompactNavigationBar();

        // 3. 主内容区
        createMainContentPanel();
    }

    private void createHeaderPanel() {
        JPanel headerPanel = new JPanel();
        headerPanel.setBackground(new Color(0, 125, 153));
        headerPanel.setPreferredSize(new Dimension(100, 50));

        JLabel lblTitle = new JLabel("上海电力大学会议预订系统");
        lblTitle.setForeground(Color.WHITE);
        lblTitle.setFont(new Font("微软雅黑", Font.BOLD, 20));

        headerPanel.add(lblTitle);
        contentPane.add(headerPanel, BorderLayout.NORTH);
    }

    private void createCompactNavigationBar() {
        JPanel navPanel = new JPanel(new GridLayout(1, 5, 0, 0));
        navPanel.setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 0));
        navPanel.setBackground(new Color(240, 240, 240));

        String[] navItems = {"首页", "我的预订", "空闲会议室", "我的信息", "退出系统"};
        for (String item : navItems) {
            JButton btn = new JButton(item);
            btn.setFont(new Font("微软雅黑", Font.PLAIN, 12));
            btn.setBackground(Color.WHITE);
            btn.setBorder(BorderFactory.createEmptyBorder(3, 0, 3, 0));
            btn.setFocusPainted(false);
            navPanel.add(btn);
        }
        contentPane.add(navPanel, BorderLayout.CENTER);
    }

    private void createMainContentPanel() {
        tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        tabbedPane.setFont(new Font("微软雅黑", Font.PLAIN, 14));

        // 添加两个选项卡
        tabbedPane.addTab("查询参加会议", createSearchPanel());
        tabbedPane.addTab("历史会议", createHistoryPanel());

        contentPane.add(tabbedPane, BorderLayout.CENTER);
    }

    private JPanel createSearchPanel() {
        JPanel panel = new JPanel(new BorderLayout(0, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        // 查询表单
        JPanel formPanel = new JPanel();
        formPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));

        // 会议号查询
        formPanel.add(new JLabel("会议号:"));
        txtMeetingId = new JTextField(10);
        formPanel.add(txtMeetingId);

        // 主持人查询
        formPanel.add(new JLabel("主持人:"));
        txtHostName = new JTextField(10);
        formPanel.add(txtHostName);

        // 查询按钮
        JButton btnSearch = new JButton("查询");
        btnSearch.addActionListener(e -> searchMeetings());
        formPanel.add(btnSearch);

        panel.add(formPanel, BorderLayout.NORTH);

        // 查询结果表格
        String[] columnNames = {"会议号", "会议名称", "主持人", "起始时间", "结束时间", "地点", "状态", "操作"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 7; // 只有"操作"列可编辑
            }
        };

        meetingTable = createStyledTable(model);
        meetingTable.getColumnModel().getColumn(7).setCellRenderer(new ButtonRenderer());
        meetingTable.getColumnModel().getColumn(7).setCellEditor(new ButtonEditor(new JCheckBox()));

        panel.add(new JScrollPane(meetingTable), BorderLayout.CENTER);

        return panel;
    }

    private JPanel createHistoryPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 查询条件面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));

        // 主持人查询
        searchPanel.add(new JLabel("主持人:"));
        JTextField txtSearchKey = new JTextField(15);
        searchPanel.add(txtSearchKey);

        // 时间范围选择
        searchPanel.add(new JLabel("时间范围:"));
        startDateChooser = new JDateChooser();
        startDateChooser.setDateFormatString("yyyy-MM-dd");
        startDateChooser.setPreferredSize(new Dimension(120, 25));
        searchPanel.add(startDateChooser);

        searchPanel.add(new JLabel("至"));
        endDateChooser = new JDateChooser();
        endDateChooser.setDateFormatString("yyyy-MM-dd");
        endDateChooser.setPreferredSize(new Dimension(120, 25));
        searchPanel.add(endDateChooser);

        // 添加本周/本月快速选择按钮
        JButton btnThisWeek = new JButton("本周");
        btnThisWeek.addActionListener(e -> setDateRangeThisWeek());
        searchPanel.add(btnThisWeek);

        JButton btnThisMonth = new JButton("本月");
        btnThisMonth.addActionListener(e -> setDateRangeThisMonth());
        searchPanel.add(btnThisMonth);

        // 查询按钮
        JButton btnSearch = new JButton("查询");
        btnSearch.addActionListener(e -> loadHistoryMeetings(txtSearchKey.getText().trim()));
        searchPanel.add(btnSearch);

        panel.add(searchPanel, BorderLayout.NORTH);

        // 结果表格
        String[] columnNames = {"会议号", "会议名称", "主持人", "起始时间", "结束时间", "地点", "状态"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);
        historyTable = new JTable(model);
        historyTable.setRowHeight(30);

        panel.add(new JScrollPane(historyTable), BorderLayout.CENTER);

        // 默认加载本月数据
        setDateRangeThisMonth();
        loadHistoryMeetings(""); // 初始加载空查询

        return panel;
    }

    private void setDateRangeThisWeek() {
        Calendar calendar = Calendar.getInstance();

        // 设置开始日期为本周一
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        startDateChooser.setDate(calendar.getTime());

        // 设置结束日期为本周日
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        endDateChooser.setDate(calendar.getTime());

        // 自动触发查询
        loadHistoryMeetings("");
    }
    private void setDateRangeThisMonth() {
        Calendar calendar = Calendar.getInstance();

        // 设置开始日期为当月第一天
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        startDateChooser.setDate(calendar.getTime());

        // 设置结束日期为当月最后一天
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        endDateChooser.setDate(calendar.getTime());
    }

    private JTable createStyledTable(DefaultTableModel model) {
        JTable table = new JTable(model);
        table.setRowHeight(30);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 12));
        table.setGridColor(new Color(220, 220, 220));
        table.setShowGrid(true);
        table.setAutoCreateRowSorter(true);
        return table;
    }

    private void searchMeetings() {
        String meetingId = txtMeetingId.getText().trim();
        String hostName = txtHostName.getText().trim();

        List<Meeting> meetings = controller.searchMeetings(meetingId,hostName);
        DefaultTableModel model = (DefaultTableModel) meetingTable.getModel();
        model.setRowCount(0);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        for (Meeting meeting : meetings) {
            Object[] row = {
                    meeting.getMID(),
                    meeting.getMname(),
                    meeting.getName(),
                    sdf.format(meeting.getMstarttime()),
                    sdf.format(meeting.getMendtime()),
                    meeting.getPlace() + " " + meeting.getLocation() + " " + meeting.getRoom(),
                    meeting.getStatus(),
                    "参加"
            };
            model.addRow(row);
        }
    }

    private void loadHistoryMeetings(String searchKey) {
        try {
            String hoseName=searchKey.trim();
            // 1. 从日期选择器获取java.util.Date
            Date utilStartDate = startDateChooser.getDate();
            Date utilEndDate = endDateChooser.getDate();

            // 2. 转换为java.sql.Timestamp
            Timestamp startTimestamp = utilStartDate != null ?
                    new Timestamp(utilStartDate.getTime()) : null;
            Timestamp endTimestamp = utilEndDate != null ?
                    new Timestamp(utilEndDate.getTime()) : null;

            // 3. 调用controller查询
            List<Meeting> meetings = controller.searchHistoryMeetings(searchKey, startTimestamp, endTimestamp);

            // 4. 更新表格数据
            DefaultTableModel model = (DefaultTableModel) historyTable.getModel();
            model.setRowCount(0); // 清空表格

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            for (Meeting meeting : meetings) {
                Object[] row = {
                        meeting.getMID(),
                        meeting.getMname(),
                        meeting.getName(),
                        sdf.format(meeting.getMstarttime()),
                        sdf.format(meeting.getMendtime()),
                        meeting.getPlace() + " " + meeting.getLocation() + " " + meeting.getRoom(),
                        meeting.getStatus()
                };
                model.addRow(row);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this,
                    "查询失败: " + ex.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }



    // 按钮渲染器和编辑器
    class ButtonRenderer extends JButton implements TableCellRenderer {
        public ButtonRenderer() {
            setOpaque(true);
        }

        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus, int row, int column) {
            setText((value == null) ? "" : value.toString());
            return this;
        }
    }

    class ButtonEditor extends DefaultCellEditor {
        private JButton button;
        private int selectedRow;

        public ButtonEditor(JCheckBox checkBox) {
            super(checkBox);
            button = new JButton();
            button.setOpaque(true);
            button.addActionListener(e -> {
                String meetingId = (String) meetingTable.getValueAt(selectedRow, 0);
                String result = controller.joinMeeting(meetingId, "current_user_id");
                JOptionPane.showMessageDialog(MeetingQueryForm1.this, result, "提示", JOptionPane.INFORMATION_MESSAGE);
                fireEditingStopped();
            });
        }

        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row, int column) {
            button.setText(value == null ? "" : value.toString());
            selectedRow = row;
            return button;
        }

        public Object getCellEditorValue() {
            return button.getText();
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                MeetingQueryForm1 frame = new MeetingQueryForm1();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
